//
//  Filter.swift
//  FeastBooking
//
//  Created by Imon on 2017/7/6.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit

class FilterButton: UIView {
    
    var status: Int = 0
    
    var image: UIImage?
    
    var selectedImage: UIImage?
    
    var sortAscString: String?
    
    var sortDescString: String?
    
    let nameLabel: UILabel = {
        let label = UILabel()
        label.font = AppFont(size: 14)
        label.textColor = UIColor.gray
        return label
    }()
    
    let imageView: UIImageView = {
        let image = UIImageView()
        return image
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.white
        self.addSubview(nameLabel)
        self.addSubview(imageView)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {        
        let textMaxSize = CGSize(width: bounds.width, height: bounds.height)
        let nameWidth = TextSize.textSize(text: nameLabel.text!, font: AppFont(size: 14), maxSize: textMaxSize).width
        let imageWid: CGFloat = 16
        self.nameLabel.frame = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(0, 0, 0, bounds.width - nameWidth))
        self.imageView.frame = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake((bounds.height - imageWid) / 2, nameWidth + 3, (bounds.height - imageWid) / 2, bounds.width - imageWid - nameWidth - 3))
    }
    
    func sortAsc() {
        nameLabel.textColor = proceededColor
        self.imageView.image = selectedImage
        self.imageView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi)
    }
    
    func sortDesc() {
        nameLabel.textColor = proceededColor
        self.imageView.image = selectedImage
        self.imageView.transform = CGAffineTransform.identity
    }
    
    func normal() {
        nameLabel.textColor = UIColor.gray
        self.imageView.image = image
        self.imageView.transform = CGAffineTransform.identity
    }
    
    func reset() {
        status = 0
        normal()
    }
    
    func touch() -> String {
        status = (status + 1) % 3
        switch status {
        case 0:
            normal()
            return ""
        case 1:
            sortAsc()
            return sortAscString != nil ? sortAscString! : ""
        case 2:
            sortDesc()
            return sortDescString != nil ? sortDescString! : ""
        default:
            return ""
        }
    }
    
    func filtered() {
        nameLabel.text = LanguageHelper.getString(key: "CANCEL")
        nameLabel.textColor = proceededColor
        self.imageView.image = selectedImage
        self.layoutSubviews()
    }
    
    func unfilterd() {
        nameLabel.text = LanguageHelper.getString(key: "FILTER")
        nameLabel.textColor = UIColor.gray
        self.imageView.image = image
        self.layoutSubviews()
    }
}
